package com.breeze.leetcode.hard;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @url <a href="https://leetcode.cn/problems/design-a-text-editor">2296. 设计一个文本编辑器</a>
 * @author yangzh
 * @date 2025/2/27
 *
 */
public class T2296TextEditor {
    private List<Character> texts;
    private int cursor;

    public static void main(String[] args) {
        T2296TextEditor textEditor = new T2296TextEditor();
        textEditor.addText("leetcode");
        System.out.println("deleteText:" + textEditor.deleteText(4));
        textEditor.addText("practice");
        System.out.println("cursorRight:" + textEditor.cursorRight(3));
        System.out.println("cursorLeft:" + textEditor.cursorLeft(8));
        textEditor.deleteText(10);
        System.out.println("cursorLeft:" + textEditor.cursorLeft(2));
        System.out.println("cursorRight:" + textEditor.cursorRight(6));
    }

    public T2296TextEditor() {
        texts = new LinkedList<>();
        cursor = 0;
    }

    public void addText(String text) {
        for (char c : text.toCharArray()) {
            texts.add(cursor++, c);
        }
    }

    public int deleteText(int k) {
        int count = 0;
        while (k > 0 && cursor > 0) {
            texts.remove(--cursor);
            count++;
            k--;
        }
        return count;
    }

    public String cursorLeft(int k) {
        cursor = Math.max(cursor - k, 0);
        int interval = Math.min(cursor, 10);
        StringBuilder res = new StringBuilder();
        for (Character ch : texts.subList(cursor - interval, cursor)) {
            res.append(ch);
        }
        return res.toString();
    }

    public String cursorRight(int k) {
        cursor = Math.min(cursor + k, texts.size());
        int interval = Math.min(cursor, 10);
        StringBuilder res = new StringBuilder();
        for (Character ch : texts.subList(cursor - interval, cursor)) {
            res.append(ch);
        }
        return res.toString();
    }
}
